package org.wangle.starter.lock.redis;

import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

import java.util.Arrays;
import java.util.Collections;


public class DoLua {

    private static RedisTemplate<String, Object> redisTemplate;

    public static String unLockScript;

    public static String lockScript;


    public static Long executeByFile(String path ,String key, Object ...param){
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setResultType(Long.class);
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource(path)));
        return redisTemplate.execute(redisScript, Collections.singletonList(key), param);
    }

    public static RedisTemplate<String, Object> getRedisTemplate(){
        return redisTemplate;
    }
    public static Long execute(String script, String[] key, Object... param){
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(script);
        redisScript.setResultType(Long.class);
        return redisTemplate.execute(redisScript, Arrays.asList(key), param);
    }

    public static void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        DoLua.redisTemplate = redisTemplate;
    }



}
